import java.io.IOException;

import javax.jms.*;
import javax.management.openmbean.CompositeData;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.jmx.QueueViewMBean;

public class Consumer {

	private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;
    private static String subject = "First message";

    private static void useJSM() throws JMSException, IOException {
    	ConnectionFactory connectionFactory
	        = new ActiveMQConnectionFactory(url);
	    Connection connection = connectionFactory.createConnection();
	    connection.start();
	
	    Session session = connection.createSession(false,
	        Session.AUTO_ACKNOWLEDGE);
	
	    Destination destination = session.createQueue(subject);
	    MessageConsumer consumer = session.createConsumer(destination);
	
	    Message message;
	    for (int i = 0; i < 1; ++i) {
	    	
	        message = consumer.receive();
	
	        if (message instanceof TextMessage) {
	            TextMessage textMessage = (TextMessage) message;
	            System.out.println("Received message '"
	                + textMessage.getText() + "'");
	        }
	    }
	    
	    connection.close();
	}
    
	private static void useJMX() throws Exception {
		
		QueueViewMBean queueViewMBean = JMXServices.getQueueViewMBean("First message");
		System.out.println(queueViewMBean.getQueueSize());
		for (CompositeData message : queueViewMBean.browse()) {
			System.out.println(message.get("Text"));
			//System.in.read();
			//queueViewMBean.removeMessage(message.get("JMSMessageID").toString());
		}
		queueViewMBean.purge();
		//System.in.read();
	}
    
    public static void main(String[] args) throws Exception {
    	// Choose you connection type
    	//useJSM();
    	useJMX();
    }
}